package com.ruoyi.management.rocketmq;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.text.CharSequenceUtil;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.constant.MQGroupConstants;
import com.ruoyi.constant.TaxiConstant;
import com.ruoyi.management.basics.service.ITCarService;
import io.swagger.models.auth.In;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.ruoyi.common.utils.sign.Base64;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * @description:
 * @author: Sunhongchen
 * @date: 2021-06-29
 */
@Service
@RocketMQMessageListener(consumerGroup = MQGroupConstants.EDU_TOPIC_GROUP_ID,
        topic = MQGroupConstants.TOPIC,
        consumeThreadMax = MQGroupConstants.consumeThreadMax)
public class TaxiMqListener implements RocketMQListener<String> {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ITCarService carService;

    @Override
    public void onMessage(String message) {
        if (StringUtils.isEmpty(message)) {
            return;
        }
        String decodeMsg = message;
        if(isBase64(message)){
            decodeMsg = Base64.getDecodeStr(message);
        }
        TaxiMessage taxiMessage = JSON.parseObject(decodeMsg, TaxiMessage.class);
       // Console.log("消费到消息：{}", message);
        // 直接发送到web端
        //wsServerEndpoint.sendMessage(JSONUtil.toJsonStr(message));
        handleTaxiMessage(taxiMessage);
    }

    private static boolean isBase64(String str) {
        String base64Pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
        return Pattern.matches(base64Pattern, str);
    }

    /**
     * 消费mq数据存redis
     *
     * @param message
     * @return void
     * @throws
     */
    private void handleTaxiMessage(TaxiMessage message) {

        MapUtils.wgs84tobd09(message);

        // 平台id_real_time_车牌号_年月日  车牌号去中文
        String carNo = CharSequenceUtil.sub(message.getCarNo(), 1, message.getCarNo().length());
        //查询公司id
        String companyKey = CharSequenceUtil.format(TaxiConstant.CAR_COMPANYID,carNo);
        Object companyId = redisTemplate.opsForValue().get(companyKey);
        if(companyId == null){
            companyId = carService.getCompanyIdByCarNo(message.getCarNo());
        }

        String redisKey = CharSequenceUtil.format(TaxiConstant.REAL_TIME_REDIS_KEY,companyId ,message.getPlatformId(), carNo, DateUtil.format(DateUtil.date(), "yyyyMMdd"));
        TaxiMessage redisObj = (TaxiMessage) redisTemplate.opsForValue().get(redisKey);
        String yesterdayKey = CharSequenceUtil.format(TaxiConstant.REAL_TIME_REDIS_KEY,companyId ,message.getPlatformId(), carNo, DateUtil.format(DateUtil.yesterday(), "yyyyMMdd"));

        //查询是否告警
        String warnKey = CharSequenceUtil.format(TaxiConstant.WARNING_CARNO,carNo);
        Object warnKeyObj = redisTemplate.opsForValue().get(warnKey);
        if (Objects.nonNull(warnKeyObj)) {
            message.setWarning(true);
        }
        if (Objects.nonNull(redisObj)) {
            //删除昨天的key
            redisTemplate.delete(yesterdayKey);
            if(!redisObj.getStatus().equals(message.getStatus())){
                String heavyKey = CharSequenceUtil.format(TaxiConstant.HEAVY_NUM_CAR_KEY, DateUtil.format(DateUtil.date(), "yyyyMMdd"),companyId);
                String emptyKey = CharSequenceUtil.format(TaxiConstant.EMPTY_NUM_CAR_KEY, DateUtil.format(DateUtil.date(), "yyyyMMdd"),companyId);
                //重车改为空车
                if(message.getStatus() == 1){
                    redisTemplate.opsForValue().increment(emptyKey,1);
                    redisTemplate.opsForValue().decrement(heavyKey,1);
                }
                //空车改为重车
                if(message.getStatus() == 2){
                    redisTemplate.opsForValue().increment(heavyKey,1);
                    redisTemplate.opsForValue().decrement(emptyKey,1);
                }
            }
            // 已存在的车辆 修改信息
            redisTemplate.opsForValue().set(redisKey, message);
            return;
        }
        // 新加入的车辆数据
        long timeout = DateUtil.endOfDay(DateUtil.date()).getTime() - DateUtil.date().getTime();
        //删除昨天的key
        redisTemplate.delete(yesterdayKey);
        // 存实时数据
        redisTemplate.opsForValue().set(redisKey, message, timeout, TimeUnit.MILLISECONDS);
        // 存今日上线车辆数
        // 今日上线车辆数
        if (!TaxiConstant.CAR_STATUS_OFFLINE.equals(message.getStatus())) {
            onlineCar((Integer) companyId);
        }
        if (TaxiConstant.CAR_STATUS_EMPTY.equals(message.getStatus())) {
            //今日空车数量
            String emptyKey = CharSequenceUtil.format(TaxiConstant.EMPTY_NUM_CAR_KEY, DateUtil.format(DateUtil.date(), "yyyyMMdd"),companyId);
            Object emptyObj = redisTemplate.opsForValue().get(emptyKey);
            if (Objects.isNull(emptyObj)) {
                // 删除昨天的key
                String yesterdayEmptyKey = CharSequenceUtil.format(TaxiConstant.EMPTY_NUM_CAR_KEY, DateUtil.format(DateUtil.yesterday(), "yyyyMMdd"),companyId);
                redisTemplate.delete(yesterdayEmptyKey);
            }
            redisTemplate.opsForValue().increment(emptyKey,1);
        }
        if (TaxiConstant.CAR_STATUS_CARRY_PASSENGER.equals(message.getStatus())) {
            //今日重车数量
            String heavyKey = CharSequenceUtil.format(TaxiConstant.HEAVY_NUM_CAR_KEY, DateUtil.format(DateUtil.date(), "yyyyMMdd"),companyId);
            Object heavyObj = redisTemplate.opsForValue().get(heavyKey);
            if (Objects.isNull(heavyObj)) {
                // 删除昨天的key
                String yesterdayHeavyKey = CharSequenceUtil.format(TaxiConstant.HEAVY_NUM_CAR_KEY, DateUtil.format(DateUtil.yesterday(), "yyyyMMdd"),companyId);
                redisTemplate.delete(yesterdayHeavyKey);
            }
            redisTemplate.opsForValue().increment(heavyKey,1);
        }
    }

    /**
     * 今日上线数量
     *
     * @return void
     * @throws
     */
    private void onlineCar(Integer companyId) {
        String redisKey = CharSequenceUtil.format(TaxiConstant.ONLINE_CAR_REDIS_KEY, DateUtil.format(DateUtil.date(), "yyyyMMdd"),companyId);
        Object redisObj = redisTemplate.opsForValue().get(redisKey);
        if (Objects.isNull(redisObj)) {
            // 删除昨天的key
            String yesterdayKey = CharSequenceUtil.format(TaxiConstant.ONLINE_CAR_REDIS_KEY, DateUtil.format(DateUtil.yesterday(), "yyyyMMdd"),companyId);
            redisTemplate.delete(yesterdayKey);
        }
        redisTemplate.opsForValue().increment(redisKey,1);
        //今日上线总数量
        String allKey = CharSequenceUtil.format(TaxiConstant.ONLINE_CAR_REDIS_KEY_ALL, DateUtil.format(DateUtil.date(), "yyyyMMdd"));
        Object allObj = redisTemplate.opsForValue().get(allKey);
        if (Objects.isNull(allObj)) {
            // 删除昨天的key
            String yesterdayKey = CharSequenceUtil.format(TaxiConstant.ONLINE_CAR_REDIS_KEY_ALL, DateUtil.format(DateUtil.yesterday(), "yyyyMMdd"));
            redisTemplate.delete(yesterdayKey);
        }
        redisTemplate.opsForValue().increment(allKey,1);
    }


}
